<template>
  <div v-if="dialogShow" v-loading="loading" :element-loading-text="loadingText">
    <div class="bread-box but20">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item class="btn-green" style=" color: #3DC094;" @click.native="goBack">卖场建设申请方案配置</el-breadcrumb-item>
        <el-breadcrumb-item>{{ formData.id ? (flag === 'edit' ? '编辑' : '详情') : '新增' }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div>
        <el-button size="mini" @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="qup-title-box">
      <span class="border" /><span>方案基础信息</span>
    </div>
    <div style="margin-bottom: 10px">
      <el-button v-if="!isEditForm && flag !== 'detail'" type="primary" size="mini" @click="handleEditForm">编辑</el-button>
      <div v-if="isEditForm">
        <el-button type="primary" size="mini" @click="handleSaveInfo">保存</el-button>
        <el-button size="mini" @click="cancel">取消</el-button>
      </div>
    </div>
    <el-form ref="ruleForm" :model="formData" size="mini" :rules="rules" label-width="120px">
      <el-row class="form_item_height">
        <el-col :span="12">
          <el-form-item label="方案编码:" size="mini" prop="programCode">
            <span>{{ formData.programCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="方案名称:" prop="programName" :required="flag !== 'detail'">
            <span v-if="flag === 'detail' || !isEditForm">{{ formData.programName }}</span>
            <el-input v-else v-model="formData.programName" placeholder="请输入方案名称" />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用最小面积:" prop="suitMinarea">
            <span v-if="flag === 'detail' || !isEditForm">{{ formData.suitMinarea }}</span>
            <el-input v-else v-model.number="formData.suitMinarea" placeholder="请输入适用最小面积" @change="checkMinArea" />
          </el-form-item>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="6" :xl="6">
          <el-form-item label="适用最大面积:" prop="suitMaxarea">
            <span v-if="flag === 'detail' || !isEditForm">{{ formData.suitMaxarea }}</span>
            <el-input v-else v-model.number="formData.suitMaxarea" placeholder="请输入适用最大面积" @change="checkMaxArea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="特殊要求备注:" size="mini" prop="specialAskRemark">
            <span v-if="flag === 'detail' || !isEditForm">{{ formData.specialAskRemark }}</span>
            <el-input v-else v-model="formData.specialAskRemark" placeholder="请输入特殊要求备注" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div>
      <div class="qup-title-box">
        <span class="border" /><span>方案区域明细</span>
      </div>
      <div v-if="flag !== 'detail'" class="btn-group">
        <el-button v-if="!isEditTable" type="primary" size="mini" @click="addArea">新增方案区域</el-button>
        <el-button v-if="showPageFlag" type="primary" size="mini" @click="editArea">编辑方案区域</el-button>
        <el-button v-if="!isEditTable" type="primary" size="mini" @click="handleDel">删除</el-button>
        <el-button v-if="!showPageFlag && isEditTable" type="primary" size="mini" @click="saveEditRow">保存编辑</el-button>
        <el-button v-if="!showPageFlag && !isEditTable" type="primary" size="mini" @click="saveNewRow">保存</el-button>
        <el-button v-if="!showPageFlag" type="primary" size="mini" @click="cancelEdit">取消</el-button>
      </div>
      <el-table
        ref="refTable"
        v-loading="tableLoading"
        element-loading-text="加载中"
        :data="tableData"
        highlight-current-row
        max-height="400"
        :header-cell-style="{background:'#F6F6F6', borderRight:'1px solid #EBEEF5'}"
        style="width: 100%; margin-top: 20px"
        @selection-change="selectionChangeHandle"
      >
        <el-table-column v-if="flag !== 'detail'" type="selection" width="55" :selectable="selectable" />
        <el-table-column prop="areaName" label="区域名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="areaDesc" label="区域说明" min-width="100">
          <template slot-scope="scope">
            <span v-if="flag === 'detail' || !scope.row.editFlag">{{ scope.row.areaDesc }}</span>
            <el-input v-else v-model="scope.row.areaDesc" size="mini" />
          </template>
        </el-table-column>
        <el-table-column prop="isMustUp" label="是否必上" min-width="100">
          <template slot-scope="scope">
            <span v-if="flag === 'detail' || !scope.row.editFlag">{{ formaterData(booleansList, scope.row.isMustUp) }}</span>
            <el-select v-if="scope.row.editFlag" v-model="scope.row.isMustUp" size="mini" placeholder="请选择是否必上" style="width:100%" @change="changeShop">
              <el-option v-for="item in booleansList" :key="item.dictCode" :label="item.dictName" :value="item.dictCode" />
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <div>
        <area-dialog v-if="showAreaDlg" ref="tipDlg" :visible.sync="showAreaDlg" :other-filter="otherFilters" @addArea="pushArea" />
        <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="handleImportSuccess" />
        <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
      </div>
    </div>
  </div>
</template>

<script>
import { getProgramFormData, getProgramData, saveProgramData, delProgramData, putProgramData, saveProgramFormData } from '@/api/marketConstruction'
import { getDictByPatchType } from '@/api/dataDict'
import AreaDialog from './areaDialog.vue'
export default {
  name: 'AddProRecommend',
  components: { AreaDialog },
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    detailData: {
      type: [String, Object],
      default: ''
    }
  },
  data() {
    return {
      exportVisible: false,
      importVisible: false,
      showAreaDlg: false,
      isEditForm: false,
      loading: false,
      loadingText: '',
      flag: '',
      showPageFlag: true,
      tableLoading: false,
      oldFormInfo: {},
      recommendProgramList: [],
      seriesNameList: [],
      enableList: [
        { dictName: '启用', dictCode: 1 },
        { dictName: '停用', dictCode: 0 }
      ],
      booleansList: [
        { dictCode: 1, dictName: '是' },
        { dictCode: 0, dictName: '否' }
      ],
      selectedRows: [],
      tableConfig: {
        pageFlag: true,
        hideFuncBar: true,
        setting: []
      },
      formData: {
        configSpace: [],
        enable: 1
      },
      rules: {
        configSpace: [{ required: true, message: '请选择所属空间/专区' }]
      },
      dataId: [],
      tableData: [],
      tableInfo: {
        currentPage: 1,
        total: '',
        rows: 10
      },
      jumpPage: '',
      allTotal: 0
    }
  },
  computed: {
    dialogShow: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    exportConfig() {
      return [{
        code: 'export',
        name: '产品上样推荐方案明细清单',
        dataApi: '/slm-admin/api/v1/configSampleDetail/export?type=0',
        selectedRows: this.selectedRows,
        paramsRaw: {},
        filtersRaw: this.dataId,
        queryField: 'id'
      },
      {
        code: 'exportTemplate',
        name: '产品上样推荐方案明细清单模板',
        async: false,
        templateMethod: 'post',
        templateApi: '/slm-admin/api/v1/configSampleDetail/export?type=1'
      }]
    },
    fileImportConfig() {
      return [{
        code: 'import',
        name: '新增产品上样推荐方案明细清单',
        async: false,
        apiUrl: '/slm-admin/api/v1/configSampleDetail/importExcel?type=1'
      },
      {
        code: 'importUpdate',
        name: '修改产品上样推荐方案明细清单',
        async: false,
        apiUrl: '/slm-admin/api/v1/configSampleDetail/importExcel?type=0'
      }]
    }
  },
  async created() {
    if (this.detailData.id) {
      this.loading = false
      this.loadingText = '加载中'
      this.flag = this.detailData.flag
      await this.getFormData()
      this.allTotal = 0
      await this.getTableData()
    }
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 格式化数据
    formaterData(arr, dictCode) {
      const tmpArr = arr.filter(item => item.dictCode === dictCode)
      if (tmpArr.length) {
        return tmpArr[0].dictName
      }
      return dictCode
    },
    formaterArr(dictList, str) {
      if (!str || !str.length) return
      let list = []
      if (typeof (str) === 'string') {
        list = str.split(',')
      } else {
        list = str
      }
      const arr = []
      dictList.forEach((item) => {
        const flag = list.some(v => v === item.dictCode)
        if (flag) {
          arr.push(item.dictName)
        }
      })
      return arr.toString()
    },
    convertDataFormat(str) {
      if (!str || !str.length) return
      const arr = str.split(',')
      return arr
    },
    // 多选框是否可选
    selectable(row) {
      if (!this.showPageFlag) {
        if (row.id) {
          return false
        }
        return true
      }
      return true
    },
    // 比较适用面积
    checkMinArea(value) {
      const area = value
      if (isNaN(area) || area < 0 || (area % 1 !== 0)) {
        this.$message.warning('请输入大于或等于0的整数')
        this.formData.suitMinarea = ''
        return
      }
      if (Number(value) > Number(this.formData.suitMaxarea)) {
        this.$message.warning('适用最小面积不可大于适用最大面积，请重新输入')
        value = ''
        this.formData.suitMinarea = ''
      }
    },
    // 比较适用面积
    checkMaxArea(value) {
      const area = value
      if (isNaN(area) || area < 0 || (area % 1 !== 0)) {
        this.$message.warning('请输入大于或等于0的整数')
        this.formData.suitMaxarea = ''
        return
      }
      if (Number(value) < Number(this.formData.suitMinarea)) {
        this.$message.warning('适用最小面积不可大于适用最大面积，请重新输入')
        value = ''
        this.formData.suitMaxarea = ''
      }
    },
    // 获取表单数据
    async getFormData() {
      this.loading = true
      this.loadingText = '加载中'
      await getProgramFormData(this.detailData.id).then(res => {
        if (res.success && res.data) {
          this.formData = res.data
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    },
    // 获取表格数据
    async getTableData(page, rows, onlyCountFlag) {
      this.tableLoading = true
      const otherFilter = [{ 'id': 'configProgramId', 'property': 'configProgramId', 'operator': '=', 'value': this.formData.id }]
      const dataForm = new FormData()
      dataForm.append('onlyCountFlag', false)
      dataForm.append('sort', 'areaIndex')
      dataForm.append('order', 'ASC')
      dataForm.append('filtersRaw', JSON.stringify(otherFilter))
      await getProgramData(dataForm).then(res => {
        if (res.success && res.data && res.data.records) {
          this.tableData = res.data.records
          this.tableData.forEach(item => {
            this.$set(item, 'editFlag', false)
          })
        }
        this.tableLoading = false
        this.showPageFlag = true
        this.isEditTable = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 获取因子组合编码集合，作为弹框过滤条件
    getOtherFilter(data) {
      if (data && data.length > 0) {
        const code = data.map(item => item.areaCode).join()
        this.otherFilters = [{ id: 'areaCode', property: 'areaCode', value: `[${code}]`, operator: 'not in' }]
      } else {
        this.otherFilters = []
      }
    },
    // 编辑表单
    handleEditForm() {
      this.oldFormInfo = JSON.parse(JSON.stringify(this.formData))
      this.isEditForm = true
    },
    // 取消编辑表单
    cancel() {
      this.formData = JSON.parse(JSON.stringify(this.oldFormInfo))
      this.isEditForm = false
      this.$refs.ruleForm.clearValidate()
    },
    // 编辑表格数据
    editArea() {
      if (!this.selectedRows.length) {
        this.$message.warning('请选择【编辑】项')
        return
      }
      this.selectedRows.forEach(item => {
        item.editFlag = true
      })
      this.isEditTable = true
      this.showPageFlag = false
    },
    // 新增
    addArea() {
      this.getOtherFilter(this.tableData)
      this.showAreaDlg = true
      this.showSaveBtn = false
      this.showPageFlag = false
      this.isEditTable = false
    },
    pushArea(data) {
      const arr1 = []
      const arr2 = []
      if (this.tableData.length === 0) {
        const dataArr = data.map(item => {
          const obj = {
            configProgramId: this.formData.id,
            configAreaId: item.id,
            areaName: item.areaName,
            areaCode: item.areaCode,
            isMustUp: 0,
            enable: 1,
            areaDesc: '',
            editFlag: true
          }
          return obj
        })
        this.tableData = [...dataArr, ...this.tableData]
        return
      }
      data.forEach(item => {
        const flag = this.tableData.some(v => v.areaCode === item.areaCode)
        if (flag) {
          arr1.push(item)
        } else {
          const row = {
            configProgramId: this.formData.id,
            configAreaId: item.id,
            areaName: item.areaName,
            areaCode: item.areaCode,
            isMustUp: 0,
            enable: 1,
            areaDesc: '',
            editFlag: true
          }
          arr2.push(row)
        }
      })
      if (arr1.length) {
        const msgArr = arr1.map(m => m.areaName)
        this.$message.warning(`${msgArr.toString()}区域已存在`)
      }
      this.tableData = [...arr2, ...this.tableData]
    },
    // 导入
    handleImport() {
      this.importVisible = true
    },
    // 导入成功
    handleImportSuccess() {
      this.getTableData()
    },
    // 导出
    handleExport() {
      this.exportVisible = true
    },
    // 删除
    handleDel() {
      if (this.selectedRows.length < 1) {
        this.$message.warning(`请选择【删除】项`)
        return false
      }
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const arr = this.selectedRows.filter(item => item.id)
        if (!arr.length) {
          if (this.selectedRows.length === this.tableData.length) {
            this.selectedRows = []
            this.$refs.refTable.clearSelection()
          } else {
            const tmpData = this.tableData.filter(row => {
              const index = this.selectedRows.findIndex(v => v.areaCode === row.areaCode)
              return index === -1
            })
            this.tableData = tmpData
            this.selectedRows = []
            this.$refs.refTable.clearSelection()
          }
          return
        }
        this.tableLoading = true
        // this.selectedRows.forEach(item => { item.dr = 1 })
        const ids = this.selectedRows.map(item => item.id)
        delProgramData(ids).then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.getTableData()
          }
          this.tableLoading = false
        }).catch(() => {
          this.tableLoading = false
        })
      })
    },
    // 取消编辑表格
    cancelEdit() {
      this.getTableData()
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.selectedRows = rows
    },
    // 返回
    goBack() {
      if (this.isEditForm || !this.showPageFlag) {
        this.$confirm('存在未保存数据，是否确认取消并返回列表界面?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dialogShow = false
          this.isEditTable = false
          this.clearForm()
          this.$emit('goBack')
        })
      } else {
        this.dialogShow = false
        this.isEditTable = false
        this.clearForm()
        this.$emit('goBack')
      }
    },
    clearForm(done) {
      this.formData = { belongRegion: 'Q001' }
      this.$refs.refForm && this.$refs.refForm.clearValidate()
      done && done()
    },
    // 保存表单
    handleSaveInfo() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.loadingText = '系统处理中'
          saveProgramFormData(this.formData).then(res => {
            if (res.success) {
              this.$message.success('操作成功')
              this.isEditForm = false
              this.getFormData()
            }
            this.loading = false
            this.loadingText = ''
          }).catch(() => {
            this.loading = false
            this.loadingText = ''
          })
        }
      })
    },
    // 保存表格--新增
    saveNewRow() {
      if (this.submiting) return
      if (!this.tableData.length) {
        this.$message.warning('请添加方案区域明细数据')
        return
      }
      const arr = this.tableData.filter(row => !row.id)
      if (!arr.length) {
        this.$message.warning('不存在未保存数据，请新增后重试')
        return
      }
      this.loading = true
      this.loadingText = '系统处理中'
      this.submiting = true
      saveProgramData(arr).then(res => {
        this.submiting = false
        if (res.success === 1) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.$nextTick(() => {
            this.getTableData()
          })
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.submiting = false
        this.loading = false
        this.loadingText = ''
      })
    },
    // 保存表格--修改
    saveEditRow() {
      this.loading = true
      this.loadingText = '系统处理中'
      putProgramData(this.tableData).then(res => {
        if (res.success) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getTableData()
        }
        this.loading = false
        this.loadingText = ''
      }).catch(() => {
        this.loading = false
        this.loadingText = ''
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.but20{ margin-bottom: 20px;}
.el-breadcrumb__inner .btn-green{
    color: #3DC094;
}
/deep/ .el-breadcrumb__inner{
  color: $qup-color-primary;
}
/deep/.el-table--mini{
  border: 1px solid #EBEEF5;
  margin-bottom: 10px;
}
</style>
